{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-10-23T14:20:08.790870Z",
     "start_time": "2019-10-23T14:19:58.596074Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Administrator\\Anaconda3\\lib\\requests\\__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.11) or chardet (3.0.4) doesn't match a supported version!\n",
      "  RequestsDependencyWarning)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "matchzoo version 1.0.2\n",
      "`ranking_task` initialized with metrics [normalized_discounted_cumulative_gain@3(0.0), normalized_discounted_cumulative_gain@5(0.0), mean_average_precision(0.0)]\n",
      "data loading ...\n",
      "data loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`\n",
      "停用表配置成功\n"
     ]
    }
   ],
   "source": [
    "%run init.ipynb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-10-23T14:10:06.000639Z",
     "start_time": "2019-10-23T14:10:05.995651Z"
    },
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "preprocessor = mz.models.MatchSRNN.get_default_preprocessor()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-10-23T14:10:30.199968Z",
     "start_time": "2019-10-23T14:10:06.004631Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval:   0%| | 0/89 [00:00<?, ?it/s]Building prefix dict from the default dictionary ...\n",
      "Loading model from cache C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\jieba.cache\n",
      "Loading model cost 1.178 seconds.\n",
      "Prefix dict has been built succesfully.\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 89/89 [00:01<00:00, 47.44it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 99/99 [00:00<00:00, 175.01it/s]\n",
      "Processing text_right with append: 100%|████████████████████████████████████████████| 99/99 [00:00<00:00, 49403.46it/s]\n",
      "Building FrequencyFilter from a datapack.: 100%|████████████████████████████████████| 99/99 [00:00<00:00, 99172.70it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 99/99 [00:00<00:00, 16505.13it/s]\n",
      "Processing text_left with extend: 100%|█████████████████████████████████████████████| 89/89 [00:00<00:00, 22255.59it/s]\n",
      "Processing text_right with extend: 100%|████████████████████████████████████████████| 99/99 [00:00<00:00, 12384.76it/s]\n",
      "Building Vocabulary from a datapack.: 100%|███████████████████████████████████| 1038/1038 [00:00<00:00, 1039562.45it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 89/89 [00:00<00:00, 108.20it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 99/99 [00:01<00:00, 86.06it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 99/99 [00:00<00:00, 49586.35it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 89/89 [00:00<00:00, 22286.15it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 99/99 [00:00<00:00, 16509.73it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 89/89 [00:00<00:00, 88921.64it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 99/99 [00:00<00:00, 49621.90it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 50/50 [00:00<00:00, 87.16it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 49/49 [00:00<00:00, 190.77it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 49/49 [00:00<00:00, 16355.32it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 50/50 [00:00<00:00, 16677.15it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 49/49 [00:00<00:00, 24510.54it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 50/50 [00:00<00:00, 50027.48it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 49/49 [00:00<00:00, 49003.55it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 29/29 [00:00<00:00, 194.75it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 30/30 [00:00<00:00, 186.45it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 30/30 [00:00<00:00, 29385.60it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 29/29 [00:00<00:00, 14567.04it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 30/30 [00:00<00:00, 15006.45it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 29/29 [00:00<00:00, 29155.04it/s]\n",
      "Processing length_right with len: 100%|██████████████████████████████████████████████| 30/30 [00:00<00:00, 6005.59it/s]\n"
     ]
    }
   ],
   "source": [
    "train_pack_processed = preprocessor.fit_transform(train_pack_raw)\n",
    "dev_pack_processed = preprocessor.transform(dev_pack_raw)\n",
    "test_pack_processed = preprocessor.transform(test_pack_raw)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-10-23T14:10:30.232878Z",
     "start_time": "2019-10-23T14:10:30.202958Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'embedding_input_dim': 349,\n",
       " 'filter_unit': <mzcn.preprocessors.units.frequency_filter.FrequencyFilter at 0x18166630908>,\n",
       " 'vocab_size': 349,\n",
       " 'vocab_unit': <mzcn.preprocessors.units.vocabulary.Vocabulary at 0x181741f5b00>}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "preprocessor.context"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-10-23T14:10:38.899753Z",
     "start_time": "2019-10-23T14:10:30.236869Z"
    },
    "collapsed": true,
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# glove_embedding = mz.datasets.embeddings.load_glove_embedding(dimension=100)\n",
    "# term_index = preprocessor.context['vocab_unit'].state['term_index']\n",
    "# embedding_matrix = glove_embedding.build_matrix(term_index)\n",
    "# l2_norm = np.sqrt((embedding_matrix * embedding_matrix).sum(axis=1))\n",
    "# embedding_matrix = embedding_matrix / l2_norm[:, np.newaxis]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-10-23T14:10:38.901741Z",
     "start_time": "2019-10-23T14:09:48.855Z"
    },
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "trainset = mz.dataloader.Dataset(\n",
    "    data_pack=train_pack_processed,\n",
    "    mode='pair',\n",
    "    num_dup=2,\n",
    "    num_neg=1\n",
    ")\n",
    "devset = mz.dataloader.Dataset(\n",
    "    data_pack=dev_pack_processed\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-10-23T14:10:38.904703Z",
     "start_time": "2019-10-23T14:09:48.860Z"
    },
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "padding_callback = mz.models.MatchSRNN.get_default_padding_callback()\n",
    "\n",
    "trainloader = mz.dataloader.DataLoader(\n",
    "    dataset=trainset,\n",
    "    stage='train',\n",
    "    callback=padding_callback,\n",
    ")\n",
    "devloader = mz.dataloader.DataLoader(\n",
    "    dataset=devset,\n",
    "    stage='dev',\n",
    "    callback=padding_callback,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-10-23T14:10:38.906698Z",
     "start_time": "2019-10-23T14:09:48.864Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MatchSRNN(\n",
      "  (embedding): Embedding(349, 100, padding_idx=0)\n",
      "  (dropout): Dropout(p=0.2, inplace=False)\n",
      "  (matching_tensor): MatchingTensor()\n",
      "  (spatial_gru): SpatialGRU(\n",
      "    (_activation): Tanh()\n",
      "    (_recurrent_activation): Sigmoid()\n",
      "    (_wr): Linear(in_features=34, out_features=30, bias=True)\n",
      "    (_wz): Linear(in_features=34, out_features=40, bias=True)\n",
      "    (_w_ij): Linear(in_features=4, out_features=10, bias=True)\n",
      "    (_U): Linear(in_features=30, out_features=10, bias=False)\n",
      "  )\n",
      "  (out): Linear(in_features=10, out_features=1, bias=True)\n",
      ")\n",
      "Trainable params:  77711\n"
     ]
    }
   ],
   "source": [
    "model = mz.models.MatchSRNN()\n",
    "\n",
    "model.params['task'] = ranking_task\n",
    "# model.params['embedding'] = embedding_matrix #这里是当加载glove等模型时取消该行注释\n",
    "#设置embedding系数\n",
    "model.params[\"embedding_output_dim\"]=100\n",
    "model.params[\"embedding_input_dim\"]=preprocessor.context[\"embedding_input_dim\"]\n",
    "model.params['channels'] = 4\n",
    "model.params['units'] = 10\n",
    "model.params['dropout'] = 0.2\n",
    "model.params['direction'] = 'lt'\n",
    "\n",
    "model.build()\n",
    "\n",
    "print(model)\n",
    "print('Trainable params: ', sum(p.numel() for p in model.parameters() if p.requires_grad))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-10-23T14:10:38.909692Z",
     "start_time": "2019-10-23T14:09:48.867Z"
    },
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "optimizer = torch.optim.Adadelta(model.parameters())\n",
    "\n",
    "trainer = mz.trainers.Trainer(\n",
    "    model=model,\n",
    "    optimizer=optimizer,\n",
    "    trainloader=trainloader,\n",
    "    validloader=devloader,\n",
    "    validate_interval=None,\n",
    "    epochs=10\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2019-10-23T14:10:38.911685Z",
     "start_time": "2019-10-23T14:09:48.872Z"
    },
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1f30cefe55f24d9da482662005948db7",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-1 Loss-1.007]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2821 - normalized_discounted_cumulative_gain@5(0.0): 0.2821 - mean_average_precision(0.0): 0.2821\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1282c84fd65c40128823658a31df1bd8",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-2 Loss-1.003]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2821 - normalized_discounted_cumulative_gain@5(0.0): 0.2821 - mean_average_precision(0.0): 0.2821\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "bc2f01cb88e0477ebc44171dd4b1061a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-3 Loss-0.955]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2821 - normalized_discounted_cumulative_gain@5(0.0): 0.2821 - mean_average_precision(0.0): 0.2821\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9f4aee7fabb748c181d645ae8e7c7a15",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-4 Loss-0.961]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2821 - normalized_discounted_cumulative_gain@5(0.0): 0.2821 - mean_average_precision(0.0): 0.2821\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "9149f3e6146f4f27bf719008deb09adb",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-5 Loss-0.979]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2821 - normalized_discounted_cumulative_gain@5(0.0): 0.2821 - mean_average_precision(0.0): 0.2821\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "afacf7f430cc4a13a0b61c15d562db68",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-6 Loss-0.923]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2821 - normalized_discounted_cumulative_gain@5(0.0): 0.2821 - mean_average_precision(0.0): 0.2821\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6f3f0f243fdb41fd806e452c476f9be1",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-7 Loss-0.965]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2821 - normalized_discounted_cumulative_gain@5(0.0): 0.2821 - mean_average_precision(0.0): 0.2821\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b87d65372a8b48cdac347e81419e076b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-8 Loss-0.903]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2821 - normalized_discounted_cumulative_gain@5(0.0): 0.2821 - mean_average_precision(0.0): 0.2821\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "56a4d9c59a404d7abe5db3f9c124dbd2",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-9 Loss-0.957]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2821 - normalized_discounted_cumulative_gain@5(0.0): 0.2821 - mean_average_precision(0.0): 0.2821\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "eab07fe60bb3421d923524d4a154b6b4",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=1), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-10 Loss-0.947]:\n",
      "  Validation: normalized_discounted_cumulative_gain@3(0.0): 0.2821 - normalized_discounted_cumulative_gain@5(0.0): 0.2821 - mean_average_precision(0.0): 0.2821\n",
      "\n",
      "Cost time: 8.525115251541138s\n"
     ]
    }
   ],
   "source": [
    "trainer.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "849"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gc\n",
    "gc.collect()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "file_extension": ".py",
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  },
  "mimetype": "text/x-python",
  "name": "python",
  "npconvert_exporter": "python",
  "pygments_lexer": "ipython3",
  "version": 3
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
